<template>
  <div class="app-container">
    <div class="filter-container">
      <span class="filter-title filter-item">状态</span>
      <k-select
        v-model="listQuery.companyStatus"
        class="filter-item right-item"
        style="width:120px"
        :select-params="[{label:'开启',value: 1},{label:'关闭',value: 2}]"
        @handleSelectEvent="handleFilter"
      />
      <k-input
        v-model.trim="listQuery.key"
        class="filter-item"
        is-search
        placeholder="进行搜索"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>

    <div v-if="authorityHandle(167)" class="top-right-btn-container">
      <k-button class="top-btn" value="添加公司" @click.native="additionCompany" />
      <k-button class="top-btn" value="紧急联系人" @click.native="setUrgentShow" />
    </div>

    <div v-else style="margin-top: 40px;" />
    <!--表格相关 -->
    <el-table
      :data="listData"
      fit
      border
      highlight-current-row
      style="width: 100%; border-radius: 8px"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
    >
      <el-table-column width="60px" type="index" label="序号" align="center" />
      <el-table-column prop="companyName" min-width="150px" label="公司名称" align="center" />
      <el-table-column prop="infoCount" min-width="150px" label="商户号数量" align="center" />

      <el-table-column prop="fissionNames" label="所属主播" align="center" show-overflow-tooltip>

        <template slot-scope="scope">
          <i
            v-if="authorityHandle(167) && scope.row.fissionNames != ''"
            style="cursor: pointer;"
            class="el-icon-document-copy"
            @click="openCopyDataShow(scope.row)"
          />
          {{ scope.row.fissionNames }}

        </template>
      </el-table-column>

      <el-table-column min-width="100px" label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.companyStatus"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开启"
            inactive-text="关闭"
            :active-value="1"
            :inactive-value="2"
            :disabled="!authorityHandle(167)"
            @change="companyStatusChange($event,scope)"
          />
        </template>
      </el-table-column>
      <el-table-column min-width="180px" label="操作" align="center">
        <template slot-scope="scope">
          <k-button v-if="authorityHandle(167)" class="table-btn" value="修改" @click.native="updateCompany(scope.row)" />
          <k-button class="table-btn" value="分配" @click.native="openDistribution(scope.row)" />
          <k-button v-if="authorityHandle(167)" class="table-btn" value="删除" @click.native="deleteCompany(scope.row)" />
        </template>
      </el-table-column>

      <el-table-column v-if="authorityHandle(167)" prop="msg" min-width="120px" label="备注" align="center">
        <editable-cell
          v-model="row.msg"
          slot-scope="{row}"
          :tool-tip-content="row.msg ? row.msg : '点击编辑,编辑完成回车'"
          :show-input="row.editMode"
          @blur="blurInput(row)"
          @keyup.enter.native="$event.target.blur()"
        >
          <span
            slot="content"
            style="
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            "
          >{{ row.msg }}</span>
        </editable-cell>
      </el-table-column>

      <el-table-column v-else prop="msg" min-width="120px" label="备注" align="center" />

    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="getListData"
    />

    <!-- 添加/修改 弹窗 -->
    <k-dialog
      :show-hide.sync="modificationShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="公司名称"
      :show-foot="false"
      :two-btn="true"
      :close-fun="closeModification"
      @click="saveModification"
    >
      <div class="warning_div">
        <el-form label-width="auto">
          <el-form-item label="公司名称：">
            <el-input v-model="companyData.companyName" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>

    <!-- 复制 弹窗 -->
    <k-dialog
      :show-hide.sync="copyDataShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      title=""
      :show-foot="false"
      :two-btn="true"
      @click="copyData"
    >
      <div class="warning_div">
        <span>公司名称：</span>
        <el-select v-model="companyValueModel" clearable placeholder="请选择">
          <el-option v-for="item in allCompany" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
        </el-select>
      </div>
    </k-dialog>

    <!-- 分配 弹窗 -->
    <k-dialog
      :show-hide.sync="distributionShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="主播分配"
      class="addBox-dialog"
      :two-btn="authorityHandle(167)"
      @click="saveDistribution"
    >
      <el-form label-width="auto" class="give_div">
        <el-form-item label="主播名称：">
          <el-select
            v-model="anchorsValueModel"
            :disabled="!authorityHandle(167)"
            multiple
            style="width: 100%;"
            filterable
            placeholder="请选择"
            @change="selectGiveAnchorChange"
          >
            <el-option v-for="item in giveAnchorList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
          </el-select>
        </el-form-item>
      </el-form>
    </k-dialog>

    <!-- 紧急联系人 弹窗 -->
    <k-dialog
      :show-hide.sync="urgentShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="紧急联系人"
      :show-foot="false"
      :two-btn="true"
      @click="saveMobileList"
    >
      <div class="warning_div">
        <el-form label-width="auto">
          <el-form-item v-for="(item,index) in mobileList" :key="index" label="手机号：">
            <el-input v-model="item.mobile" placeholder="请输入手机号码" />
            <i v-show="index > 0" class="el-icon-circle-close" style="cursor: pointer;" @click="deleteItem(index)" />
            <i
              v-show="index == mobileList.length - 1"
              class="el-icon-circle-plus-outline"
              style="margin-left: 5px; color: #08c81b; cursor: pointer;"
              @click="addItem()"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>

  </div>
</template>

<script>
import { saveCompany, listCompanyData, updateCompany, updateStatus, deleteCompany, fissionList, companyFission, assignCompany, companyList, copyAssignCompany, getUrgentMobile, setUrgentMobile } from '@/api/company/index.js'
import EditableCell from '@/components/EditableCell'
import Pagination from '@/components/Pagination'
export default {
  name: 'Company',
  components: { EditableCell, Pagination },
  data() {
    return {
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10
        },
        companyStatus: undefined, // 状态1开|2关",
        key: '' // 关键字'
      },
      listData: [],
      totalRows: 0,

      // 添加/修改
      modificationType: 'addition',
      modificationShow: false,
      companyData: {
        id: undefined,
        companyName: '',
        msg: ''
      },

      // 复制
      copyDataShow: false,
      lineId: undefined,
      allCompany: [],
      companyValueModel: '',

      // 分配
      distributionShow: false,
      companyId: undefined,
      anchorsValueModel: [],
      giveAnchorList: [],

      // 紧急联系人
      urgentShow: false,
      mobileList: [
        {
          mobile: ''
        }
      ]
    }
  },

  created() {
    this.getListData()
  },

  methods: {
    // 紧急联系人 弹框
    setUrgentShow() {
      getUrgentMobile().then(res => {
        if (res.data.length > 0) {
          const list = []
          for (let i = 0; i < res.data.length; i++) {
            list.push({
              mobile: res.data[i]
            })
          }
          this.mobileList = list
        }
        this.urgentShow = true
      })
    },

    // 保存
    saveMobileList() {
      const list = this.mobileList.map(item => item.mobile)
      const status = list.every(item => item.trim().length == 11)
      if (!status) {
        this.$message.error('请输入正确的手机格式！')
        return
      }
      setUrgentMobile({ list: list }).then(res => {
        this.$message.success('保存成功')
        this.urgentShow = false
      })
    },

    // 删除
    deleteItem(index) {
      this.mobileList.splice(index, 1)
    },

    // 添加
    addItem() {
      this.mobileList.push({ mobile: '' })
    },

    // list数据
    getListData() {
      listCompanyData(this.listQuery).then(res => {
        const data = res.data
        this.totalRows = data.totalRows
        if (data.rows) {
          this.listData = data.rows.map(row => {
            return {
              ...row,
              editMode: false
            }
          })
        } else {
          this.listData = []
        }
      })
    },

    // 搜索查询事件
    handleFilter() {
      this.listQuery.pager.pageNo = 1
      this.getListData()
    },

    // 添加
    additionCompany() {
      this.modificationType = 'addition'
      this.companyData.id = undefined
      this.companyData.companyName = ''
      this.companyData.msg = ''
      this.modificationShow = true
    },

    // 修改
    updateCompany(row) {
      this.companyData = row
      this.modificationType = 'update'
      this.modificationShow = true
    },

    // 添加/修改(保存)
    saveModification() {
      if (this.companyData.companyName == '') {
        this.$message.error('请输入公司名称')
        return
      }
      if (this.modificationType === 'addition') {
        // 添加
        saveCompany(this.companyData).then(res => {
          if (res.data.success) {
            this.$message.success('添加成功')
            this.listQuery.pager.pageNo = 1
            this.getListData()
            this.modificationShow = false
          } else {
            this.$message.error(res.data.msg)
          }
        })
      } else {
        // 修改
        updateCompany(this.companyData).then(res => {
          if (res.data.success) {
            this.$message.success('修改成功')
            this.listQuery.pager.pageNo = 1
            this.getListData()
            this.modificationShow = false
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
    },

    // 添加/修改(取消)
    closeModification() {
      this.getListData()
      this.modificationShow = false
    },

    // 公司开关
    companyStatusChange(event, scope) {
      const id = scope.row.id
      updateStatus({ 'id': id }).then(res => {
        if (res.data.success) {
          this.getListData()
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.data.msg)
          scope.row.mcStatus = event === 0 ? 1 : 0
        }
      })
    },

    // 备注
    blurInput(row) {
      if (row.msg.trim() != '') {
        updateCompany({ id: row.id, msg: row.msg }).then(res => {
          if (res.data.success) {
            this.$message.success('备注成功')
            this.getListData()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
    },

    // 删除(二次确认)
    deleteCompany(row) {
      this.$confirm('是否删除当前公司', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteCompanyInfo(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },

    // 删除
    deleteCompanyInfo(row) {
      deleteCompany({ id: row.id }).then(res => {
        if (res.data.success) {
          this.$message.success('删除成功')
          this.listQuery.pager.pageNo = 1
          this.getListData()
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    // 复制
    openCopyDataShow(row) {
      this.lineId = row.id
      companyList().then(res => {
        this.companyValueModel = ''
        const data = res.data
        this.allCompany = data.filter(item => item.lineId != this.lineId)
        this.copyDataShow = true
      })
    },

    // 复制(保存)
    copyData() {
      copyAssignCompany({ id: this.companyValueModel, oldId: this.lineId }).then(res => {
        if (res.data.success) {
          this.$message.success('保存成功')
          this.listQuery.pager.pageNo = 1
          this.getListData()
          this.copyDataShow = false
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    // 分配
    openDistribution(row) {
      this.companyId = row.id
      fissionList({ status: 'normal' }).then(res => {
        this.giveAnchorList = res.data
        companyFission({ id: row.id }).then(res => {
          this.anchorsValueModel = res.data
          this.distributionShow = true
        })
      })
    },

    // 选择
    selectGiveAnchorChange(value) {
      this.anchorsValueModel = value
    },

    // 分配保存
    saveDistribution() {
      const data = {
        id: this.companyId,
        fissionIds: this.anchorsValueModel
      }
      assignCompany(data).then(res => {
        if (res.data.success) {
          this.$message.success('保存成功')
          this.getListData()
          this.distributionShow = false
        } else {
          this.$message.error(res.data.msg)
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
$menuText: #14162E; // 侧边栏字体颜色
$hoverColor: #1D143C; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }

  .right-item {
    margin-right: 10px;
  }

  .kInput {
    position: absolute;
    right: 20px;
  }

  .filter-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162E;
  }

  .user-item {
    margin-left: 10px;
    margin-right: 20px;
  }

  .user-status,
  .account-status {
    margin-right: 20px;
  }
}

.top-right-btn-container {
  position: relative;

  .top-btn {
    margin: 30px 20px 30px 0px;
    font-size: 14px;
    color: #ffffff;
  }

  .top-right-btn {
    position: absolute;
    right: 20px;
    top: 30px;
    background-color: #F8F7FB;
    border-color: $mainColor;
    color: #14162E;

    &:hover {
      color: #ffffff;
      background-color: $mainColor;
    }

    &:active {
      color: #14162E;
    }

  }

  .top-right-btn-left {
    position: absolute;
    right: 140px;
    top: 30px;
    background-color: #F8F7FB;
    border-color: $mainColor;
    color: #14162E;

    &:hover {
      color: #ffffff;
      background-color: $mainColor;
    }

    &:active {
      color: #14162E;
    }

  }
}

.cell {
  i {
    color: #3b425d;
    margin-left: 8px;
    font-size: 18px;
  }
}

.warning_div {
  padding: 50px 120px;

  span {
    font-size: 18px;
  }

  ::v-deep .el-input {
    width: 280px;
    margin: 0 6px;
  }

  ::v-deep .el-select .el-input.is-focus .el-input__inner {
    border-color: #3b425d;
  }

  ::v-deep .el-select .el-input__inner:focus {
    border-color: #3b425d;
  }
}

.give_div {
  margin: 0 auto;
  width: 800px;
  height: 400px;
  padding: 0 50px 50px;
  box-sizing: border-box;

  ::v-deep .el-input {
    width: 100%;
  }
}

::v-deep .edit-cell {
  .input-div {
    .el-input__inner {
      height: 50px;
    }
  }
}
</style>
